import { BaseView } from './../../rxjs/cc3/BaseView';
import { _decorator, Node, PageView, UITransform, CCFloat } from 'cc';
import { CCBindPageView } from '../../rxjs/cc3/BindPageView';
const { ccclass, property } = _decorator;

@ccclass('LeanDynamicPageView')
export class LeanDynamicPageView extends BaseView {

    @property(PageView)
    pageView: PageView = null;

    @property(Node)
    contentNode: Node = null;

    @property(CCFloat)
    visibleSize: number = 0;

    get itemSize() {
        return this.pageView.getComponent(UITransform).width;
    }

    get itemSizeSub() {
        return this.pageView.getComponent(UITransform).height;
    }

    currentItems: Record<number, Node> = {};

    isGenerated: boolean = false;

    useObserves() {
        return [
            CCBindPageView(this.pageView).subscribe(_ => {
                if (_.state == 'scrolling') this.pageViewScrolling();
            })
        ];
    }

    pageViewScrolling() {
        let _tempCurrentRow: Record<number, Node> = {};
        for (let key in this.currentItems) {
            if (this.idxNeedShow(Number(key))) {
                _tempCurrentRow[key] = this.currentItems[key];
            } else {
                this.recycleRow(Number(key));
            }
        }
        this.currentItems = _tempCurrentRow;
        this.traverseNeedShow(idx => {
            if (this.currentItems[idx] == null) {
                this.genRow(idx);
            }
        });
    }

    isOpen: boolean = false;

    // 开启列表，开始生成项
    openPageView() {
        if (!this.isGenerated) {
            this.generateRows();
            this.isOpen = true;
        }
    }

    // 继承后覆盖，给出列表总大小
    getDataCount() {
        return 10;
    }

    // 对象池相关，需要重写。回收container所有的item节点
    putAllChildren(container: Node) {
        container.destroyAllChildren();
    }

    // 对象池相关，需要重写。从池中获得一个Item节点
    getItemNode(): Node {
        return new Node();
    }

    // 对象池相关，需要重写。向池中返还一个Item节点
    putItemNode(node: Node) {
        node.destroy();
    }

    generateRows() {
        this.pageView.removeAllPages();
        for (let i = 0; i < this.getDataCount(); i++) {
            let node = new Node(`page${i}`);
            let transform = node.addComponent(UITransform);
            transform.width = this.itemSize;
            transform.height = this.itemSizeSub;
            this.pageView.addPage(node);
        }

        this.traverseNeedShow(idx => {
            this.genRow(idx);
        });

        this.isGenerated = true;
    }

    getFirstNeedShowProgress() {
        let start_p = -this.visibleSize / 2;
        let diff = -this.contentNode.position.x + start_p;
        let idx = Math.floor(diff / this.itemSize);
        return idx;
    }

    getLastNeedShowProgress() {
        let end_p = this.visibleSize / 2;
        let diff = -this.contentNode.position.x + end_p;
        let idx = Math.floor(diff / this.itemSize);
        return idx;
    }

    /** 遍历需要显示的节点的progress */
    traverseNeedShow(call: (idx: number, order: number) => void) {
        let firstIdx = this.getFirstNeedShowProgress();
        let lastIdx = this.getLastNeedShowProgress();
        let order = 0;
        for (let idx = firstIdx; idx <= lastIdx; idx++) {
            if (idx >= 0 && idx < this.getDataCount()) {
                call(idx, order);
                order++;
            }
        }
    }

    idxNeedShow(idx: number): boolean {
        let firstIdx = this.getFirstNeedShowProgress();
        let lastIdx = this.getLastNeedShowProgress();
        if (idx >= firstIdx && idx <= lastIdx) {
            if (idx >= 0 && idx <= this.getDataCount()) {
                return true;
            }
        }
        return false;
    }

    refreshShowed() {
        this.traverseNeedShow(idx => {
            if (this.currentItems[idx] == null) {
                this.genRow(idx);
            } else {
                this.refreshRow(idx);
            }
        });
    }

    genRow(idx: number) {
        let node = this.getItemNode();
        node.setParent(this.contentNode.children[idx]);
        node.setPosition(0, 0, 0);
        this.currentItems[idx] = node;
        this.refreshRow(idx);
    }

    recycleRow(idx: number) {
        let node = this.currentItems[idx];
        delete this.currentItems[idx];
        this.putItemNode(node);
    }

    // 继承后覆盖这个方法，刷新item
    refreshRow(idx: number) {
    }

    // 获得显示头page和尾page时的content位置;
    getContentRange() {
        const head = -this.itemSize / 2;
        const tail = -this.itemSize * this.getDataCount() + this.itemSize / 2;
        return [head, tail];
    }

}

